package com.mass.core.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;

public class ResourcesFileUtils {

	public static String path;    //存储文件路径
	
	/**
	 * 将InputStream写入本地文件
	 * @param destination 写入本地目录     例如ResourcesFileUtils.getResourcesFilePath("ueditor-config.json")
	 * @param input	输入流
	 * @throws IOException
	 * 
	 *  InputStream in = this.getClass().getResourceAsStream("/files/aa.xls");
	 *  或
	 *  Resource resource = new ClassPathResource("static/excel/table.xlsx");
		InputStream input = resource.getInputStream();
		注： this.getClass().getResourceAsStream("");指向的路径问Resource跟目录，可以根据目录路径来写自己的文件路径。
		注：如果文件路径或者文件名中存在中文，路径也会访问不到。所以文件路径和文件尽量使用英文。可以在输出文件的时候，修改文件名为中文。
	 */
	public static String getResourcesFilePath(String resourcesFilePath) {
		try{
			String filePath = path+"/resources/"+resourcesFilePath;
			File serFile = new File(filePath.substring(0, filePath.lastIndexOf("/"))); 
            if (!serFile.exists()) {
            	serFile.mkdirs();
            }
			ClassLoader classloader = Thread.currentThread().getContextClassLoader();
	        InputStream input = classloader.getResourceAsStream(resourcesFilePath);
            //ResourceLoader resourceLoader = new DefaultResourceLoader();
            //String fileFullPath = "classpath:/"+resourcesFilePath;
            //InputStream input = resourceLoader.getResource(fileFullPath).getInputStream();
			int index;
			byte[] bytes = new byte[1024];
			FileOutputStream downloadFile = new FileOutputStream(filePath);
			while ((index = input.read(bytes)) != -1) {
				downloadFile.write(bytes, 0, index);
				downloadFile.flush();
			}
			downloadFile.close();
			input.close();
			return filePath;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	public static String getFileContext(String resourcesFilePath){
		 ClassLoader classloader = Thread.currentThread().getContextClassLoader();
		 InputStream stencilsetStream = classloader.getResourceAsStream(resourcesFilePath);
	     try {
			return IOUtils.toString(stencilsetStream, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
